package com.aijia.custom.product.manager;

import android.content.Context;

import com.aijia.custom.product.data.LoginResponse;
import com.aijia.custom.product.http.Batch;
import com.aijia.custom.product.http.Command;
import com.aijia.custom.product.http.HttpUtil;
import com.aijia.custom.product.http.JsonUtil;
import com.aijia.custom.product.listener.ILogin;
import com.aijia.custom.product.listener.ILoginListener;
import com.aijia.custom.product.logical.Action;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;

/**
 * 登录接口
 * Created by yejianjun on 2019/1/16.
 */

public class LoginManager implements ILogin {

    private ILoginListener mListener = null;
    private Context _context;

    public LoginManager(Context context) {
        _context = context;
    }


    @Override
    public void login(String username, String password) {
        // 向平台发送登录请求
        StringEntity stringEntity = null;
        try {
            Command command = new Command();
            command.addAction(Action.ACTION_LOGIN)
                    .addArgs("username", username)
                    .addArgs("password", password);
            stringEntity = new StringEntity(Batch.build().addCommand(command).toJson(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        HttpUtil http = new HttpUtil();
        http.req(_context, stringEntity, false, new HttpUtil.MyResponse() {

            @Override
            public void responseSucess(Object obj) {
                // TODO Auto-generated method stub
                LoginResponse resp = JsonUtil.toObject(obj, LoginResponse.class);
                // 通知界面
                if (null != mListener)
                    mListener.onLoginSuccess(resp);
            }

            @Override
            public void responseFailure(int errorCode, String msg) {
                // TODO Auto-generated method stub
                if (null != mListener)
                    mListener.onLoginFailure(errorCode, msg);
            }
        });
    }

    @Override
    public boolean addLoginListener(ILoginListener listener) {
        mListener = listener;
        return mListener != null;
    }

    @Override
    public boolean removeLoginListener(ILoginListener listener) {
        if (null == listener)
            return false;
        mListener = null;
        return true;
    }
}
